// simple_admin.js
// 一个简化版的管理员用户初始化脚本，使用原生SQL查询

require('dotenv').config();
const { sequelize } = require('../utils/database');
const bcrypt = require('bcryptjs');

async function createAdminUser() {
  console.log('开始创建管理员用户...');
  
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 1. 检查admin用户是否存在
    const [adminUsers] = await sequelize.query(`
      SELECT id, username, email, role FROM users WHERE username = 'admin';
    `);
    
    if (adminUsers.length > 0) {
      console.log('管理员用户已存在:', adminUsers[0]);
      
      // 2. 更新admin用户角色
      await sequelize.query(`
        UPDATE users 
        SET role = 'admin',
            permissions = '{"user.view":true,"user.edit":true,"user.delete":true,"user.status":true,"content.review":true,"content.edit":true,"content.delete":true,"badge.view":true,"badge.create":true,"badge.mint":true,"system.stats":true}'
        WHERE username = 'admin';
      `);
      console.log('管理员用户角色已更新');
    } else {
      console.log('管理员用户不存在，开始创建...');
      
      // 3. 创建管理员用户
      const password = 'admin123';
      const password_hash = await bcrypt.hash(password, 12);
      
      await sequelize.query(`
        INSERT INTO users (username, email, password_hash, bio, role, permissions, is_active, createdAt, updatedAt)
        VALUES ('admin', 'admin@campus.com', ?, '系统管理员', 'admin', 
        '{"user.view":true,"user.edit":true,"user.delete":true,"user.status":true,"content.review":true,"content.edit":true,"content.delete":true,"badge.view":true,"badge.create":true,"badge.mint":true,"system.stats":true}', 
        1, NOW(), NOW());
      `, {
        replacements: [password_hash]
      });
      console.log('管理员用户创建成功!');
      console.log('用户名: admin');
      console.log('密码: admin123');
    }
    
    // 4. 检查superadmin用户是否存在
    const [superAdminUsers] = await sequelize.query(`
      SELECT id, username, email, role FROM users WHERE username = 'superadmin';
    `);
    
    if (superAdminUsers.length === 0) {
      console.log('超级管理员用户不存在，开始创建...');
      
      // 5. 创建超级管理员用户
      const password = 'superadmin123';
      const password_hash = await bcrypt.hash(password, 12);
      
      await sequelize.query(`
        INSERT INTO users (username, email, password_hash, bio, role, is_active, createdAt, updatedAt)
        VALUES ('superadmin', 'superadmin@campus.com', ?, '系统超级管理员', 'superadmin', 1, NOW(), NOW());
      `, {
        replacements: [password_hash]
      });
      console.log('超级管理员用户创建成功!');
      console.log('用户名: superadmin');
      console.log('密码: superadmin123');
    } else {
      console.log('超级管理员用户已存在:', superAdminUsers[0]);
      
      // 6. 确保角色是superadmin
      await sequelize.query(`
        UPDATE users SET role = 'superadmin' WHERE username = 'superadmin';
      `);
    }
    
    console.log('✅ 管理员用户初始化完成!');
    
  } catch (error) {
    console.error('管理员用户初始化失败:', error);
  } finally {
    // 关闭数据库连接
    await sequelize.close();
  }
}

// 如果直接运行此脚本，则执行初始化
if (require.main === module) {
  createAdminUser();
}

module.exports = createAdminUser; 